package com.zj.controller;

import com.zj.generator.domain.Myuser;
import com.zj.generator.service.MyuserService;
import com.zj.pojo.Apple;
import com.zj.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private MyuserService service;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String CACHE_PRI = "user:";

    @PostMapping("/addone")
    @ResponseBody
    public Result addUser(@RequestBody Myuser myuser) {
        log.info("addUser:" + myuser);
        boolean ret = service.save(myuser);
        System.out.println("xxx" + myuser.getId());
        if (ret) {
            Myuser userByName = myuser;
            if (myuser.getId() < 2) {
                userByName = service.getUserByName(myuser.getUserName());
            }
            redisTemplate.opsForValue().set(CACHE_PRI + userByName.getId(), myuser);

        }
        return new Result<>(HttpStatus.OK.value(), "insert success", ret);
    }

    @GetMapping("/{id}")
    public Result getUser(@PathVariable int id) {
        log.info("getUser:" + id);
        String key = CACHE_PRI + id;
        Myuser myuser = null;
        myuser = (Myuser) redisTemplate.opsForValue().get(key);
        if (myuser == null) {
            myuser = service.getById(id);
            if (myuser == null) {
                redisTemplate.opsForValue().set(key, Strings.EMPTY);
            } else {
                redisTemplate.opsForValue().set(key, myuser);
            }
        }

        return new Result(HttpStatus.OK.value(), "query success", myuser);
    }
}
